package com.jike.jkgame;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

import kankan.wheel.R;
import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.OnWheelScrollListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.AbstractWheelAdapter;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.jike.jkgame.data.Mission;
import com.jike.jkgame.data.Status;
import com.jike.jkgame.data.UserStatus;
import com.jike.jkgame.ui.UserStatusBar;
import com.jike.jkgame.widget.AutoScrollTextView;

public class TestMainActivity extends Activity implements OnClickListener {

	private CountDownTimer mCountDownTask;
	private UserStatusBar mStatusBar;
	private boolean mContinueMusic = false;
	private WheelView mWheel;
	private boolean mWheelScrolled = false;
	
	private XMPPConnection mXmppConnection;
	private ChatManager mChatmanager;
	private Chat mChat;
	private EditText mChatMsgEt;
	private TextView mRecivedMsgTv;
	
	private AutoScrollTextView mBroadCastTv;

	private Handler mHandler = new Handler(new Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			String name = (String) msg.obj;
			if (name == null) {
				return false;
			}

			mStatusBar.updateStatusView(UserStatus.get().getStatusByName(name),
					msg.arg1);
			return false;
		}
	});

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		testResourceFile();
		
		if (!checkLogin()) {
			Intent intent = new Intent(TestMainActivity.this, LoginActivity.class);
			startActivity(intent);
			finish();
		}
		
		setContentView(R.layout.activity_main);

		findViewById(R.id.btn_use_health).setOnClickListener(this);
		findViewById(R.id.btn_use_energy).setOnClickListener(this);
		findViewById(R.id.btn_use_all).setOnClickListener(this);
		findViewById(R.id.btn_start_wheel).setOnClickListener(this);
		findViewById(R.id.btn_send).setOnClickListener(this);

		mChatMsgEt = (EditText) findViewById(R.id.et_msg);
		mRecivedMsgTv = (TextView) findViewById(R.id.tv_recived_msg);
		
		mStatusBar = new UserStatusBar(
				(ViewGroup) findViewById(R.id.user_statusbar), UserStatus.get());

		UserStatus.get().getVigour().setTargetHandler(mHandler);
		UserStatus.get().getEnergy().setTargetHandler(mHandler);
		
		initWheel();
		
		initLoginXMPP();
		
	}
	
	private void testResourceFile() {
		try {
			InputStream in = getAssets().open("task.dat");
			Mission.parsDataFile(in);
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_use_health: {
			UserStatus status = UserStatus.get();
			Status health = status.getVigour();
			health.use(10);
			break;
		}
		case R.id.btn_use_energy: {
			UserStatus status = UserStatus.get();
			Status energy = status.getEnergy();
			energy.use(10);
			break;
		}
		case R.id.btn_start_wheel: {
			mixWheel();
			break;
		}
		case R.id.btn_send:{
			sendMassage();
			break;
		}
		default:
			break;
		}

	}
	
	private void sendMassage() {
		
		if (mXmppConnection == null || !mXmppConnection.isConnected()) {
			return;
		}
		
		if (mChatmanager == null) {
			mChatmanager = mXmppConnection.getChatManager();
		}
		
		if(mChat == null) {
			mChat = mChatmanager.createChat("wumailjing@gmail.com", new MessageListener() {

				@Override
				public void processMessage(Chat chat,
						org.jivesoftware.smack.packet.Message message) {
					try {
						chat.sendMessage("Re: " + message.getBody());
					} catch (XMPPException e) {
						e.printStackTrace();
					}
					mRecivedMsgTv.setText(message.getBody());
				}
			});
		}
		
		try {
			String msg = mChatMsgEt.getText().toString();
			mChat.sendMessage(msg);
			mChatMsgEt.setText("");
		}
		catch (XMPPException e) {
		    e.printStackTrace();
		}
	}
	
	private void initLoginXMPP() {
		ConnectionConfiguration connConfig = new 
		          ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
		mXmppConnection = new XMPPConnection(connConfig);
		SASLAuthentication.supportSASLMechanism("PLAIN", 0);
	    try {
	    		mXmppConnection.connect();
	    		mXmppConnection.login("race604@gmail.com", "wujingw5jin9");
			
	    		// Add a packet listener to get messages sent to us
	            PacketFilter filter = new MessageTypeFilter(org.jivesoftware.smack.packet.Message.Type.chat);
	            mXmppConnection.addPacketListener(new PacketListener() {
	                public void processPacket(Packet packet) {
	                	final org.jivesoftware.smack.packet.Message message = (org.jivesoftware.smack.packet.Message) packet;
	                    if (message.getBody() != null) {
	                        final String fromName = StringUtils.parseBareAddress(message.getFrom());
	                        Log.i("XMPPClient", "Got text [" + message.getBody() + "] from [" + fromName + "]");
	                        
	                        // Add the incoming message to the list view
	                        mHandler.post(new Runnable() {
	                            public void run() {
	                                mRecivedMsgTv.setText(fromName + ":" + message.getBody());
	                            }
	                        });
	                    }
	                }
	            }, filter);

			// Assume we've created a Connection name "connection".
	    		
		} catch (XMPPException e) {
			e.printStackTrace();
		}    
	    
	}
	
	// Wheel scrolled listener
    OnWheelScrollListener scrolledListener = new OnWheelScrollListener() {
        public void onScrollingStarted(WheelView wheel) {
            mWheelScrolled = true;
        }
        public void onScrollingFinished(WheelView wheel) {
        		mWheelScrolled = false;
            updateStatus();
        }
    };
    
    // Wheel changed listener
    private OnWheelChangedListener changedListener = new OnWheelChangedListener() {
        public void onChanged(WheelView wheel, int oldValue, int newValue) {
            if (!mWheelScrolled) {
                updateStatus();
            }
        }
    };
    
    /**
     * Updates status
     */
    private void updateStatus() {
    	
    }
	
    /**
     * Initializes wheel
     */
    private void initWheel() {
        mWheel = (WheelView) findViewById(R.id.slot_1);
        mWheel.setViewAdapter(new SlotMachineAdapter(this));
        mWheel.setCurrentItem((int)(Math.random() * 10));
        
        mWheel.addChangingListener(changedListener);
        mWheel.addScrollingListener(scrolledListener);
        mWheel.setCyclic(true);
        mWheel.setEnabled(false);
        mWheel.setVisibleItems(2);
    }
    
    /**
     * Mixes wheel
     */
    private void mixWheel() {
        mWheel.scroll(-350 + (int)(Math.random() * 50), 5000);
    }

	@Override
	protected void onResume() {
		super.onResume();
		mContinueMusic = false;
		//MusicManager.start(this, MusicManager.MUSIC_GAME);
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (!mContinueMusic) {
			MusicManager.pause();
		}
	}
	
	private boolean checkLogin() {
		// TODO
		return false;
	}
    
    /**
     * Slot machine adapter
     */
    private class SlotMachineAdapter extends AbstractWheelAdapter {
        // Image size
        final int IMAGE_WIDTH = 60;
        final int IMAGE_HEIGHT = 36;
        
        // Slot machine symbols
        private final int items[] = new int[] {
                android.R.drawable.star_big_on,
                android.R.drawable.stat_sys_warning,
                android.R.drawable.radiobutton_on_background,
                android.R.drawable.ic_delete
        };
        
        // Cached images
        private List<SoftReference<Bitmap>> images;
        
        // Layout inflater
        private Context context;
        
        /**
         * Constructor
         */
        public SlotMachineAdapter(Context context) {
            this.context = context;
            images = new ArrayList<SoftReference<Bitmap>>(items.length);
            for (int id : items) {
                images.add(new SoftReference<Bitmap>(loadImage(id)));
            }
        }
        
        /**
         * Loads image from resources
         */
        private Bitmap loadImage(int id) {
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id);
            Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true);
            bitmap.recycle();
            return scaled;
        }

        @Override
        public int getItemsCount() {
            return items.length;
        }

        // Layout params for image view
        final LayoutParams params = new LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);
        
        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            ImageView img;
            if (cachedView != null) {
                img = (ImageView) cachedView;
            } else {
                img = new ImageView(context);
            }
            img.setLayoutParams(params);
            SoftReference<Bitmap> bitmapRef = images.get(index);
            Bitmap bitmap = bitmapRef.get();
            if (bitmap == null) {
                bitmap = loadImage(items[index]);
                images.set(index, new SoftReference<Bitmap>(bitmap));
            }
            img.setImageBitmap(bitmap);
            
            return img;
        }
    }

}
